#include "activation.h"
#include "ui_activation.h"

#include <QDebug>
#include <QFileInfo>
#include<QProcess>
//#include "activationsystemdbus.h"
#include "receive_dbus.h"
#include <QString>
#include <QStringList>
#include <QMessageBox>
#include <QKeyEvent>
#include <QTimer>
#include <QRegExpValidator>
#include <QStyleOption>
#include <QPainter>
#include "kwindowsystem.h"
//#ifdef __cplusplus
extern "C" {
#include <kylin-activation.h>
}

gint canset_serial_flag = 0;
QString newserial = "";
gint serial_edit_flag = 1;
gint customer_edit_flag = 1;

//窗口构建
ActivationWidget::ActivationWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ActivationWidget)
{
    ui->setupUi(this);
//    systeminterface = new SystemDispatcher(this);
    this->init_data();
//    this->setWindowIcon(QIcon(":/res/kylin-activation.png"));

    this->thread = new activation_thread();
//    this->thread->start();
    KWindowSystem::setState(this->winId(),NET::SkipTaskbar | NET::SkipPager);
    kms_activation = new activation_thread_kms();

    connect(kms_activation, SIGNAL(activation_post_signal(QString)),this, SLOT(send_activation_info(QString)));
    connect(this->m_accessManager_Registered, SIGNAL(finished(QNetworkReply*)),this, SLOT(finishedSlot_info(QNetworkReply*)));


    init_ui();
    connect(this->thread, SIGNAL(signal_ukey_activation()), this, SLOT(ukey_activation()));

//    m_sysActiveMainWindow=new SystemActivationMainWindow(this);
}

//窗口析构函数
ActivationWidget::~ActivationWidget()
{
//    if (systeminterface != NULL)
//    {
//        delete systeminterface;
//        systeminterface = NULL;
//    }
    exit_service();
//    delete m_sysActiveMainWindow;
    delete ui;
}

void ActivationWidget::paintEvent(QPaintEvent *event){
    Q_UNUSED(event);
    QStyleOption opt;
    QPainter p(this);
    opt.init(this);
    p.setBrush(opt.palette.base().color());
    p.setPen(Qt::NoPen);
    p.drawRect(opt.rect);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
//    style()->drawPrimitive(QStyle::PE_PanelLineEdit, &opt, &p, this);
}
//初始化ui
void ActivationWidget::init_ui()
{
//    ui->status->setStyleSheet("QLabel{font:bold;font-size:18px;color:#FF293D}");
    ui->status->setAlignment(Qt::AlignCenter);
    ui->label_6->setAlignment(Qt::AlignLeft | Qt::AlignTop);
//    ui->label_6->setStyleSheet("QLabel{background-color:red}");
}

//激活界面数据初始化函数
void ActivationWidget::init_data()
{
    gint state = 1, dbus_init_flag = 0;
    QString state_date = NULL;
    QString re_error = "Error ";
    QString customer_txt = "";
    QFont font;

    ui->serial_value->setReadOnly(true);
//    ui->serial_value->setStyleSheet("QLineEdit{border-width:0;border-style:outset}");
    ui->serial_value->setValidator(new QRegExpValidator(QRegExp("[0-9]+$")));
    ui->serial_value->setMaxLength(20);
    ui->serial_edit->hide();
    ui->customer_value->setReadOnly(true);
//    ui->customer_value->setStyleSheet("QLineEdit{border-width:0;border-style:outset}");
    ui->customer_value->setMaxLength(20);


//    int serial_num = 0;
//    int registration_num = 0;
//    int qrcode_num = 0;
    dbus_init_flag = dbus_init();
    if(! dbus_init_flag)
    {
        QMessageBox::warning(this, NULL, QString(tr("Dbus Error!")));
        exit_service();
        qApp->exit(0);
    }

    QStringList *rtnlist = NULL;
    if( can_set_serial() )
    {
        canset_serial_flag = 1;
        ui->serial_edit->show();
         rtnlist = byte8_get_init_data();
    }
    else
    {
        canset_serial_flag = 0;
        rtnlist = byte6_get_init_data();
    }

    state = status_code();
    if(state == 1)
        ui->customer_edit->hide();


//    serial = systeminterface->get_serial_number_qt();
//    registration = systeminterface->get_register_number_qt();
//    url = systeminterface->get_qrcode_qt();

    font.setCapitalization(QFont::AllUppercase);
    ui->activation_value->setFont(font);
    ui->activation_value_2->setFont(font);
    ui->activation_value_3->setFont(font);
    ui->activation_value_4->setFont(font);
    ui->activation_value_5->setFont(font);

//    ui->confirm->setShortcut(Qt::Key_Return);
//    ui->confirm->setShortcut(Qt::Key_Enter); //设置快捷键为enter键


    ui->serial->setText(tr("serial number:"));
//    ui->serial->setText("序列号：");
    ui->registration->setText(tr("License:"));
//    ui->registration->setText("注册码：");
    ui->customer->setText(tr("Customer:"));
    ui->url->setText(tr("Activation URL:"));
//    ui->url->setText("激活码网址：");
    ui->label->setText(tr("Scan code acquisition"));
    ui->label->setAlignment(Qt::AlignCenter);
//    ui->label->setText("扫描获取激活码");
    ui->label_6->setText(tr("Please fill in the activation code or insert Ukey:"));
//    ui->label_6->setText("请填写激活码或插入Ukey后进行激活：");
//    ui->activation->setText(tr("Activation:"));
//    ui->activation->setText("激活码：");
    ui->confirm->setText(tr("Code activation"));
//    ui->confirm->setText("激活码激活");
    ui->confirm_2->setText(tr("Ukey activation"));
//    ui->confirm_2->setText("Ukey激活");

#ifdef ENABLE_UKEY
    ui->confirm_2->show();
#else 
    ui->confirm_2->hide();
#endif



    state_date = status_date();

    if(state == 1)
        ui->status->setText(tr("Has been activated, the expiration time:")+state_date);
//        ui->status->setText("您的系统已激活,到期时间："+state_date);
    else{
        if(state_date != "" )
            ui->status->setText(tr("Has expired, the expiration time:")+state_date);
//            ui->status->setText("您的系统已过期，过期时间："+state_date);
        else
            ui->status->setText(tr("Your system is not activated, please activate!"));
//            ui->status->setText("您的系统还未激活，请激活！");
    }

    if (rtnlist->at(1) == "0")
    {
        newserial = rtnlist->at(0);
        ui->serial_value->setText(rtnlist->at(0));
    }
    else if(rtnlist->at(1) == "")
        ui->serial_value->setText("");
    else
        ui->serial_value->setText(tr("File system test failure! (error code#") + rtnlist->at(1).rightJustified(4,'0')  +")");
//        ui->serial_value->setText("系统文件检测失败！(错误码#" + rtnlist->at(1).rightJustified(4,'0')  +")");

    this->displayeinfo(rtnlist);

    customer_txt = get_customer();
    ui->customer_value->setText(customer_txt);
}

//显示获取的数据信息
void ActivationWidget::displayeinfo(QStringList  *rtnlist)
{

    if(rtnlist->at(3)== "0")
        ui->registration_value->setText(rtnlist->at(2));
    else if(rtnlist->at(3) == "")
        ui->registration_value->setText("");
    else
        ui->registration_value->setText(tr("File system test failure! (error code#") + rtnlist->at(3).rightJustified(4,'0')  +")");
//    ui->registration_value->setText("系统文件检测失败！(错误码#" + rtnlist->at(3).rightJustified(4,'0')  +")");

    if(rtnlist->at(5)== "0")
    {
        QString qurl = "<a href = '"+ rtnlist->at(4) +"' > "+rtnlist->at(4)+" </a>";
        ui->url_value ->setOpenExternalLinks(true);
        ui->url_value->setText(qurl);

        int fontSize = fontMetrics().width( rtnlist->at(4) );//获取之前设置的字符串的像素大小
        if( fontSize >= ui->url_value->width() ) //与label自身相比较
        {

            QString str = fontMetrics().elidedText( rtnlist->at(4), Qt::ElideRight, ui->url_value->width() );//返回一个带有省略号的字符串
            qurl = "<a href = '"+ rtnlist->at(4) +"' > "+str+" </a>";
            ui->url_value->setText( qurl );       //重新设置label上的字符串

        }

        QFileInfo filepng("/tmp/kylin-qrcode.png");
        if(filepng.isFile())
            QFile::remove("/tmp/kylin-qrcode.png");
        QProcess p(0);
        QString qrurl = "qrencode -t png -o /tmp/kylin-qrcode.png  ";
        qrurl.append(rtnlist->at(4));
        qDebug() << qrurl;
        p.start(qrurl);
        p.waitForStarted();
        p.waitForFinished();
//        ui->qr_code->setStyleSheet("QLabel{border-image:url('/tmp/kylin-qrcode.png');}");
        filepng.setFile("/tmp/kylin-qrcode.png");
        if(filepng.isFile())
            system("chmod 777 /tmp/kylin-qrcode.png");
     }
    else if(rtnlist->at(5) == "")
        ui->url_value->setText("");
    else
        ui->url_value->setText(tr("File system test failure! (error code#") + rtnlist->at(5).rightJustified(4,'0')  +")");
//        ui->url_value->setText("系统文件检测失败！(错误码#" + rtnlist->at(5).rightJustified(4,'0')  +")");

}

//激活按钮点击
void ActivationWidget::on_confirm_clicked()
{
    ui->confirm->setText(tr("Activation..."));
//    ui->confirm->setText("激活中...");
    ui->confirm->setEnabled(false);
    ui->confirm->repaint();
    ui->confirm->repaint();  //通过事件提前触发重绘
//    QTimer myTimer ;

    QString result = ui->activation_value->text().toUpper() +  ui->activation_value_2->text().toUpper() + ui->activation_value_3->text().toUpper() + ui->activation_value_4->text().toUpper() +ui->activation_value_5->text().toUpper();
    qDebug() << result;
    if  (result == ""){
        QMessageBox::warning(this, NULL, QString(tr("Activation is empty!  ")));
//        QMessageBox::about(this, "提示", QString("激活码为空！  "));
    }
    else{
        gint activation= 1;
        QString ret = tr("Invalid activation code");
        QByteArray ba = newserial.toLatin1();
//        QString ret = "无效激活码";
        if(canset_serial_flag == 0)
            activation = active_code(result.toLatin1().data());
        else
        {
            activation = new_active_code(ba.data(), result.toLatin1().data());
        }
        ret = kylin_activation_get_result_message(activation);
        if(ret == "")
            ret = tr("Invalid activation code");
//            ret = "无效激活码";
        if (activation == 0)
        {
            kms_activation->start();
//            myTimer.start(3000);
             QMessageBox *box=new QMessageBox(QMessageBox::Warning, NULL, QString(tr("Activation is successful, reboot the system!")),QMessageBox::NoButton,this);
             QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
             box->setDefaultButton(closeButton);
//            QMessageBox::about(this, "提示", QString("激活成功,请重启系统！"));
//            connect(&myTimer,SIGNAL(timeout()),box,SLOT(close()));
            box->exec();
            exit_service();
            delete box;
            qApp->exit(0);
        }
        else
        {
            QMessageBox::warning(this,  NULL, QString(ret+ tr("!(error code#" )+ QString::number(activation).rightJustified(4,'0')  +")"));

//            QMessageBox::about(this, "提示", QString(ret+ "！(错误码#" + QString::number(activation).rightJustified(4,'0')  +")"));
        }
    }
    ui->confirm->setText(tr("Code activation"));
//    ui->confirm->setText("激活码激活");
    ui->confirm->setEnabled(true);
//    qDebug() << result;
//    qDebug() << activation;
//    qDebug() << active_code("abcdefg");
}

//激活码输入1
void ActivationWidget::on_activation_value_textChanged(const QString &arg1)
{
    if (arg1.length() >=4) {
        ui->activation_value_2->setFocus();
    }
}

//激活码输入2
void ActivationWidget::on_activation_value_2_textChanged(const QString &arg1)
{
    if (arg1.length() >=4) {
        ui->activation_value_3->setFocus();
    }
}

//激活码输入3
void ActivationWidget::on_activation_value_3_textChanged(const QString &arg1)
{
    if (arg1.length() >=4) {
        ui->activation_value_4->setFocus();
    }
}

//激活码输入4
void ActivationWidget::on_activation_value_4_textChanged(const QString &arg1)
{
    if (arg1.length() >=4) {
        ui->activation_value_5->setFocus();
    }
}

//激活码输入5
void ActivationWidget::on_activation_value_5_textChanged(const QString &arg1)
{
    if (arg1.length() >=4) {
        ui->confirm->setFocus();
    }
}


void ActivationWidget::keyPressEvent(QKeyEvent  *event)
{
    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
        {
            on_confirm_clicked();//按钮槽函数
        }
}

//ukey激活按钮点击
void ActivationWidget::on_confirm_2_clicked()
{
//    QTimer myTimer;

    ui->confirm_2->setEnabled(false);
    ui->confirm_2->setText(tr("Activation..."));
//    ui->confirm_2->setText("激活中...");

    ui->confirm_2->repaint();
    ui->confirm_2->repaint();  //通过事件提前触发重绘

    gint activation= 1;
    QString ret = tr("Ukey not inserted or invalid Ukey");
//    QString ret = "未插入Ukey或无效Ukey";
    activation = active_code("");
    ret = kylin_activation_get_result_message(activation);
    if(ret == "")
        ret = tr("Ukey not inserted or invalid Ukey");
//        ret = "未插入Ukey或无效Ukey";
    if (activation == 0)
    {
        kms_activation->start();
//        myTimer.start(3000);
         QMessageBox *box=new QMessageBox(QMessageBox::Warning, NULL, QString(tr("Activation is successful, reboot the system!")),QMessageBox::NoButton,this);
         QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
         box->setDefaultButton(closeButton);
//            QMessageBox::about(this, "提示", QString("激活成功,请重启系统！"));
//        connect(&myTimer,SIGNAL(timeout()),box,SLOT(close()));
        box->exec();

        exit_service();
        delete box;
        qApp->exit(0);
    }
    else
    {
        QMessageBox::warning(this,  NULL, QString(ret+ tr("!(error code#" )+ QString::number(activation).rightJustified(4,'0')  +")"));
//        QMessageBox::about(this, "提示", QString(ret+ "！(错误码#" + QString::number(activation).rightJustified(4,'0')  +")"));
    }
    ui->confirm_2->setText(tr("Ukey activation"));
//    ui->confirm_2->setText("Ukey激活");
    ui->confirm_2->setEnabled(true);
}

// ukey自动激活调用
//ukey激活按钮点击
void ActivationWidget::ukey_activation()
{
//    QTimer myTimer;
    gint activation= 1;
    activation = active_code("");

    if(flag == 0 && activation != 20) //激活状态锁，error 20:未检测到有效Ukey
    {
        ui->confirm_2->setEnabled(false);
        ui->confirm_2->setText(tr("Activation..."));
    //    ui->confirm_2->setText("激活中...");
        ui->confirm_2->repaint();  //通过事件提前触发重绘


        QString ret = tr("Ukey not inserted or invalid Ukey");
    //    QString ret = "未插入Ukey或无效Ukey";

        ret = kylin_activation_get_result_message(activation);
        if(ret == "")
            ret = tr("Ukey not inserted or invalid Ukey");
    //        ret = "未插入Ukey或无效Ukey";

        if (activation == 0) // 激活成功
        {
            kms_activation->start();
            flag = 1;
//            myTimer.start(3000);
             QMessageBox *box=new QMessageBox(QMessageBox::Warning, NULL, QString(tr("Activation is successful, reboot the system!")),QMessageBox::NoButton,this);
             QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
             box->setDefaultButton(closeButton);
    //            QMessageBox::about(this, "提示", QString("激活成功,请重启系统！"));
//            connect(&myTimer,SIGNAL(timeout()),box,SLOT(close()));
            box->exec();

            exit_service();
            delete box;
            flag = 0;
            qApp->exit(0);
        }
        else  // 激活失败
        {
            flag = 1;
            QMessageBox::warning(this,  NULL, QString(ret+ tr("!(error code#" )+ QString::number(activation).rightJustified(4,'0')  +")"));
            flag = 0;
        }

        ui->confirm_2->setText(tr("Ukey activation"));
    //    ui->confirm_2->setText("Ukey激活");
        ui->confirm_2->setEnabled(true);
    }
}

void ActivationWidget::on_serial_edit_clicked()
{
    if(serial_edit_flag == 1)
    {
        serial_edit_flag =0;
        ui->serial_edit->setText(tr("OK"));
        ui->serial_value->setReadOnly(false);
        ui->serial_value->setFocus();
    }
    else if(serial_edit_flag == 0)
    {
        gchar * input_serial;
        QString qst_input;
        qst_input = ui->serial_value->text();
        QByteArray ba = qst_input.toLatin1();
        input_serial = ba.data();

        QStringList *rtnlist = new QStringList();
        QStringList *tmp = NULL;
        rtnlist->append(input_serial);
        rtnlist->append("0");
        if(strlen(input_serial) < 8)
            QMessageBox::warning(this, NULL, QString(tr("Serial number needs to be greater than 7 digits!")));
        else
        {
            serial_edit_flag =1;
            ui->serial_edit->setText(tr("Edit"));
            ui->serial_value->setReadOnly(true);

            tmp = new_register_number(input_serial);
            rtnlist->append(tmp->at(0));
            rtnlist->append(tmp->at(1));
            if(rtnlist->at(3)== "77" )
                QMessageBox::warning(this, NULL, QString(tr("Please enter the correct serial number!")));
            else
            {
                newserial = qst_input;
                tmp = new_qrcode(input_serial);
                rtnlist->append(tmp->at(0));
                rtnlist->append(tmp->at(1));
                this->displayeinfo(rtnlist);
            }
        }

    }
}

void ActivationWidget::on_customer_edit_clicked()
{
    if(customer_edit_flag == 1)
    {
        customer_edit_flag =0;
        ui->customer_edit->setText(tr("OK"));
        ui->customer_value->setReadOnly(false);
        ui->customer_value->setFocus();
    }
    else if(customer_edit_flag == 0)
    {
        QString  input_customer;
        input_customer = ui->customer_value->text();

        set_customer(input_customer.toLocal8Bit().data());
        customer_edit_flag =1;
        ui->customer_edit->setText(tr("Edit"));
        ui->customer_value->setReadOnly(true);
    }

}

//局域网自动激活
void ActivationWidget::slot_activation_message(int activation)
{
    qDebug() << "receivetcp 44";

    if (activation == 0)
    {
//        myTimer.start(3000);
        kms_activation->start();
         QMessageBox *box=new QMessageBox(QMessageBox::Warning, NULL, QString(tr("Activation is successful, reboot the system!")),QMessageBox::NoButton,this);
         QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
         box->setDefaultButton(closeButton);
//            QMessageBox::about(this, "提示", QString("激活成功,请重启系统！"));

//        connect(&myTimer,SIGNAL(timeout()),box,SLOT(close()));

         box->exec();
         delete box;
    }
    else
    {
        QMessageBox::warning(this,  NULL, QString(tr("Invalid activation code")+"!"));

//        QMessageBox::about(this, "提示", QString(ret+ "！(错误码#" + QString::number(activation).rightJustified(4,'0')  +")"));
    }
    exit_service();
    qApp->exit(0);
//    ui->confirm_2->setText(tr("Ukey activation"));
//    ui->confirm_2->setText("Ukey激活");
//    ui->confirm_2->setEnabled(true);
}


void ActivationWidget::send_activation_info(QString info)
{
    qDebug()<<"send_info:1111" ;
    QUrl Url ;
    QString config_path = QDir::homePath() + "/.config/activation_conf.ini";
    QFileInfo file(config_path);
    QString rename = "cp " + config_path + " " + config_path + ".bak";

    char * ch;
    QByteArray ba = rename.toLatin1();
    ch=ba.data();
    if(file.exists()==true)
        system(ch);



    Url.setUrl("https://wx.kylinos.cn/api/upload_hwinfo/v1");
    QByteArray sendData = info.toLocal8Bit();
//    Url = Url + info;

//    QString Url = "http://ubuntukylin.com:10081/getMCodeByPhone?";
//    Url = Url + QString::fromUtf8("phone=18274869690") ;

    qDebug()<<"send_info:2222" ;
    QNetworkRequest request = QNetworkRequest(Url);
    qDebug()<<"send_info:3333" ;
    request.setRawHeader("Accept", "*/*");
    request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9");
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
    request.setRawHeader("X-Requested-With:", "XMLHttpRequest");
    QNetworkReply* registered = m_accessManager_Registered->post(request, sendData);

    qDebug()<<"send_info:4444" ;

//    QUrlQuery postData;
//    postData.addQueryItem("username", user_name);
//    postData.addQueryItem("password", md5(user_passwd));
    //        qDebug() << tr("注册的用户名：") + user_name + tr("注册的密码：") + md5(user_passwd);

            //发起POST请求 预留代码
//    QNetworkReply* registered = m_accessManager_Registered->post(request_registered,postData.toString(QUrl::FullyEncoded).toUtf8());

//    QNetworkReply* registered = m_accessManager_Registered->get(request_registered);
    qDebug()<<"send_info:5555" ;
    qDebug()<<"send_info:" <<registered;



}

int ActivationWidget::finishedSlot_info(QNetworkReply *registered)
{
    QString config_path = QDir::homePath() + "/.config/activation_conf.ini";
    QString bak_path = config_path + ".bak";
    QFileInfo file(bak_path);
    QString rename = "cp " + bak_path + " "  + config_path;

    char * ch;
    QByteArray ba = rename.toLatin1();
    ch=ba.data();

    qDebug( "finishedSlot_sendinfo");
    if (registered->error() == QNetworkReply::NoError)
    {
        // 获取响应信息
        QByteArray bytes = registered->readAll();      //读取所有字节；

        QJsonParseError jsonError;
        //转化为JSON文档
        QJsonDocument doucment = QJsonDocument::fromJson(bytes, &jsonError);
        // 解析Json  error
        if (doucment.isObject()) {
            QJsonObject obj = doucment.object();
            qDebug() << "打印obj";
            qDebug() << obj;

            QJsonValue val;
        //            jwt::claim payload;
            if (obj.contains("errcode")) {
                val = obj.value("errcode");
                if(val.toInt() == 0){
                    qDebug() << "send info success!";
                    if(file.exists()==true)
                        system(ch);
                    return 0;
                }
                else{
                    qDebug() << "send info error:"<<obj.value("errcode").toString();
                    return val.toString().toInt();
                }
            }

        }
        if (jsonError.error != QJsonParseError::NoError) {
            qDebug() << QStringLiteral("解析Json失败");
            return 101;
        }
        }
        else
        {
        qDebug()<<"handle errors here";
        QVariant statusCodeV = registered->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        //statusCodeV是HTTP服务器的相应码，reply->error()是Qt定义的错误码，可以参考QT的文档
        return 102;
        }

        registered->deleteLater();
}

void ActivationWidget::on_qrcodebtn_clicked()
{
//    m_sysActiveMainWindow->show();
//    m_sysActiveMainWindow->raise();
//    m_sysActiveMainWindow->activateWindow();
}
